package com.qianniu.napi.admin.web;

import akka.actor.ActorRef;
import akka.actor.Props;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.*;
import com.qianniu.napi.admin.mapper.CoupontplMemberMapper;
import com.qianniu.napi.admin.mapper.MdpayMapper;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.admin.service.akka.AkkaServer;
import com.qianniu.napi.admin.service.akka.OrderActor;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.*;
import org.jdom.JDOMException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@RestController
public class PayController {

    private static final Logger logger = LoggerFactory.getLogger(PayController.class);

    @Autowired
    private IUserService userService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private ICzfanService czfanService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private IAccountService accountService;
    @Autowired
    private IMaccountService maccountService;
    @Autowired
    private IMaccountFlowService maccountFlowService;
    @Autowired
    private IOrderRefundService orderRefundService;
    @Autowired
    private ICouponService couponService;
    @Autowired
    private ICouponTplService couponTplService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private MdpayMapper mdpayMapper;
    @Autowired
    private CoupontplMemberMapper coupontplMemberMapper;
    @Autowired
    private IQnpay qnpay;

    /**
     * 门店版小程序充值
     *
     * @param money 充值金额
     * @param fan   饭钱数
     * @param jifen 返积分数
     * @return
     */
    @RequestMapping("/api/recharge/pay")
    @ResponseBody
    public Jinfo rechargePay(@RequestParam("money") BigDecimal money,
                             @RequestParam("fan") BigDecimal fan,
                             @RequestParam(value = "jifen", required = false) BigDecimal jifen,
                             HttpServletRequest req) {
        Jinfo json = new Jinfo();
        if (money.doubleValue() <= 0) {
            json.setCode(1);
            json.setInfo("充值金额有误");
            return json;
        }

        String ip = ObjectUtil.getIP();
        Long mid = ObjectUtil.getMid();
        Long mpid = ObjectUtil.getMpid();
        Long uid = ObjectUtil.getUid();
        User user = redisService.getUser();

        Order order = new Order();
        order.setUid(uid);
        order.setMid(mid);
        order.setMpid(mpid);
        order.setRealpay(money);
        order.setPrices(money);
        order.setTotal(money);
        order.setStatus(1);
        order.setState(1);
        order.setOrderType(0);
        order.setPayType(2);
        order.setGoodsName("在线充值");
        order.setGoodsNumber(1);
        order.setGtype(GtypeEnum.none.getVal());
        order.setType(YXType.common.getVal());//订单类型
        order.setXftype(XftypeEnum.recharge.getVal());//订单类型
        order.setLinkman(user.getNickName());
        order.setPhone(user.getPhone());
        order.setOrderNo(StringUtil.getSnNo("C"));
        order.setShortno(orderService.getShortno(ObjectUtil.getMpid()));

        BigDecimal zero = new BigDecimal(0);
        AccountFlow af = new AccountFlow();
        af.setRealpay(money);
        af.setAmount(zero);
        af.setDikou(fan == null ? zero : fan);// 营销金额=赠送红包金额
        af.setTotal(af.getRealpay().add(af.getAmount()).add(af.getDikou()));

        af.setNickname(user != null ? user.getNickName() : null);
        af.setHeadimg(user != null ? user.getAvatarPic() : null);
        af.setPhone(user != null ? user.getPhone() : null);
        Account act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
        if (act == null) {
            act = accountService.initAccount(uid, mid, mpid);
        }
        af.setUid(uid);
        af.setMid(mid);
        af.setMpid(ObjectUtil.getMpid());
        af.setState(1);
        af.setIotype(IotypeEnum.input.getVal());//1:入账
        af.setXftype(XftypeEnum.recharge.getVal());//1:充值
        af.setIsConfirm(-1);//未确认
        af.setCreatetime(new Date());
        af.setSn(order.getOrderNo());
        af.setRemark("在线充值" + money.toString());
        af.setTradetime(new Date());
        af.setCreatetime(new Date());
        af.setLasttotal(act.getTotal());
        af.setLastamount(act.getAmount());
        af.insert();

        MerchantConfig mc = redisService.getMconfig();
        if ((jifen != null && jifen.doubleValue() > 0) ||
                (mc.getIsJifen() != null && mc.getIsJifen() == 1 && mc.getFanjifenType() != null && mc.getFanjifenType() > 0)) {

            JifenFlow jf = new JifenFlow();

            if (jifen != null && jifen.doubleValue() > 0) jf.setNum(jifen);//充值金额（元）取整
            else jf.setNum(money);//充值金额（元）取整

            jf.setSn(af.getSn());
            jf.setIsConfirm(-1);
            jf.setState(1);
            jf.setIotype(IotypeEnum.input.getVal());//积分+
            jf.setJftype(JftypeEnum.recharge.getVal());//消费充值返积分
            jf.setCreatetime(new Date());
            jf.setUid(uid);
            jf.setMid(mid);
            jf.setMpid(ObjectUtil.getMpid());
            jf.setRemark("消费充值奖励积分");
            jf.insert();
        }

        MaccountFlow maf = new MaccountFlow();
        maf.setUid(uid);
        maf.setMid(mid);
        maf.setState(1);
        maf.setIotype(IotypeEnum.input.getVal());//1:入账
        maf.setXftype(XftypeEnum.recharge.getVal());//1:充值
        maf.setAmount(money);
        maf.setMamount(fan);
        maf.setIsConfirm(-1);//未确认
        maf.setSn(af.getSn());
        maf.setRemark("会员在线充值");
        maf.setTradetime(new Date());
        maf.setCreatetime(maf.getTradetime());
        maf.insert();

        Map<String, String> map = qnpay.minappPay(mid, ObjectUtil.getAppid(), uid, money, af.getRemark(), af.getSn(), ip, order);
        if (!map.containsKey("package")) {
            json.setCode(1);
        } else {
            map.put("oid", af.getId().toString());//paySign加密
        }

        json.setInfo(map);
        return json;
    }

    /**
     * 门店版小程序充值，充值返礼品
     *
     * @param money 充值金额
     * @param czid  返礼品ID
     * @return
     */
    @RequestMapping("/api/recharge/pay2")
    @ResponseBody
    public Jinfo rechargePay2(@RequestParam("money") BigDecimal money,
                              @RequestParam(value = "czid", required = false) Long czid) {
        Jinfo json = new Jinfo();
        if (money.doubleValue() <= 0) {
            json.setCode(1);
            json.setInfo("充值金额有误");
            return json;
        }

        String ip = ObjectUtil.getIP();
        Long mid = ObjectUtil.getMid();
        Long mpid = ObjectUtil.getMpid();
        Long uid = ObjectUtil.getUid();
        User user = redisService.getUser();

        Order order = new Order();
//        order.setGid(czid);
        order.setUid(uid);
        order.setMid(mid);
        order.setMpid(mpid);
        order.setRealpay(money);
        order.setPrices(money);
        order.setTotal(money);
        order.setStatus(1);
        order.setState(1);
        order.setOrderType(0);
        order.setPayType(2);
        order.setGoodsName("在线充值");
        order.setGoodsNumber(1);
        order.setGtype(GtypeEnum.recharge.getVal());
        order.setXftype(XftypeEnum.recharge.getVal());
        order.setType(YXType.common.getVal());
        order.setLinkman(user.getNickName());
        order.setPhone(user.getPhone());
        order.setOrderNo(StringUtil.getSnNo("C"));
        order.setShortno(orderService.getShortno(ObjectUtil.getMpid()));

        //给做头士多商家分账
        BigDecimal zero = new BigDecimal(0);
        order.setLmfan(zero);
        order.setPtfan(zero);
        order.setSharefan(zero);
        order.setMinprice(money);

        Czfan czfan = new Czfan();

        BigDecimal jifen = zero;
        if (czid != null && czid > 0) {
            czfan = czfanService.selectById(czid);
        }

        AccountFlow af = new AccountFlow();
        af.setRealpay(money);
        af.setAmount(zero);
        if (czfan != null) af.setDikou(czfan.getFancash() == null ? zero : czfan.getFancash());
        af.setTotal(af.getRealpay().add(af.getAmount()).add(af.getDikou()));

        af.setNickname(user != null ? user.getNickName() : null);
        af.setHeadimg(user != null ? user.getAvatarPic() : null);
        af.setPhone(user != null ? user.getPhone() : null);
        Account act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
        if (act == null) {
            act = accountService.initAccount(uid, mid, mpid);
        }
        af.setUid(uid);
        af.setMid(mid);
        af.setMpid(mpid);
        af.setState(1);
        af.setOrigin(czid == null ? "" : czid.toString());
        af.setIotype(IotypeEnum.input.getVal());//1:入账
        af.setXftype(XftypeEnum.recharge.getVal());

        af.setIsConfirm(-1);//未确认
        af.setCreatetime(new Date());
        af.setSn(order.getOrderNo());
        af.setRemark("在线充值" + money.toString());
        af.setTradetime(new Date());
        af.setCreatetime(new Date());
        af.setLasttotal(act.getTotal());
        af.setLastamount(act.getAmount());
        af.insert();

        MerchantConfig mc = redisService.getMconfig();
//        if ((czfan != null && czfan.getFanjifen() > 0) ||
//                (mc.getIsJifen() != null && mc.getIsJifen() == 1 && mc.getFanjifenType() != null && mc.getFanjifenType() > 0)
//                ) {

        MaccountFlow maf = new MaccountFlow();
        maf.setUid(uid);
        maf.setMid(mid);
        maf.setMid(mpid);
        maf.setState(1);
        maf.setIotype(IotypeEnum.input.getVal());//1:入账
        maf.setXftype(XftypeEnum.recharge.getVal());//1:充值
        maf.setAmount(money);

        if (czfan != null) maf.setMamount(czfan.getFancash() == null ? zero : czfan.getFancash());
        maf.setIsConfirm(-1);//未确认
        maf.setSn(af.getSn());
        maf.setRemark("会员在线充值");
        maf.setTradetime(new Date());
        maf.setCreatetime(maf.getTradetime());
        maf.insert();


        if (czfan != null && czfan.getFanjifen() != null && czfan.getFanjifen().doubleValue() > 0) {

            jifen = czfan.getFanjifen();

            JifenFlow jf = new JifenFlow();
            jf.setNum(jifen);//充值金额（元）取整

            jf.setSn(af.getSn());
            jf.setIsConfirm(-1);
            jf.setState(1);
            jf.setIotype(IotypeEnum.input.getVal());//积分+
            jf.setJftype(JftypeEnum.recharge.getVal());//积分返消费
            jf.setCreatetime(new Date());
            jf.setUid(uid);
            jf.setMid(mid);
            jf.setMpid(ObjectUtil.getMpid());
            jf.setRemark("充值奖励积分");
            jf.insert();
        }

        if (czfan != null && czfan.getFanbi() != null && czfan.getFanbi().doubleValue() > 0) {

            XnbiFlow xnbiFlow = new XnbiFlow();
            xnbiFlow.setNum(jifen);//充值金额（元）取整

            xnbiFlow.setSn(af.getSn());
            xnbiFlow.setIsConfirm(-1);
            xnbiFlow.setState(1);
            xnbiFlow.setIotype(IotypeEnum.input.getVal());//积分+
            xnbiFlow.setJftype(JftypeEnum.recharge.getVal());//积分返消费
            xnbiFlow.setCreatetime(new Date());
            xnbiFlow.setUid(uid);
            xnbiFlow.setMid(mid);
            xnbiFlow.setMpid(mpid);
            xnbiFlow.setRemark("充值奖励虚拟币");
            xnbiFlow.insert();
        }

        Map<String, String> map = qnpay.minappPay(mid, ObjectUtil.getAppid(), uid, money, af.getRemark(), af.getSn(), ip, order);
        if (!map.containsKey("package")) {
            json.setCode(1);
        } else {
            map.put("oid", af.getId().toString());//paySign加密
            // 开通
            User u = userService.selectById(uid);
            if (u.getIsMember() != 1) {
                u.setIsMember(1);
                u.setIsEcashCard(1);
                u.insertOrUpdate();
            }
        }

        json.setInfo(map);
        return json;
    }

    /**
     * 配送小程序购买会员
     *
     * @param money 充值金额
     * @param czid  返礼品ID
     * @return
     */
    @RequestMapping("/api/recharge/pay3")
    @ResponseBody
    public Jinfo rechargePay3(@RequestParam("money") BigDecimal money,
                              @RequestParam(value = "czid", required = false) Long czid) {
        Jinfo json = new Jinfo();
        if (money.doubleValue() <= 0) {
            json.setCode(1);
            json.setInfo("充值金额有误");
            return json;
        }

        String ip = ObjectUtil.getIP();
        Long mid = ObjectUtil.getMid();
        Long mpid = ObjectUtil.getMpid();
        Long uid = ObjectUtil.getUid();
        Long sid = ObjectUtil.getSid();
        BigDecimal zero = new BigDecimal(0);
        User user = redisService.getUser();

        Goods goods = goodsService.selectById(-4);//会员购买
        Order order = new Order();
        order.setGid(-4l);//购买会员
        order.setPic(goods == null ? null : goods.getThumb());
        order.setUid(uid);
        order.setMid(mid);
        order.setMpid(mpid);
        order.setSid(sid);
        Store store = redisService.getStore(sid);
        order.setSname(store == null ? null : store.getName());

        order.setRealpay(money);
        order.setGoodsName("会员购买");
        order.setSaleprice(money);
        order.setPrice(money);
        order.setPrices(money);
        order.setTotal(money);
        order.setDeduction(zero);
        order.setDiscount(zero);
        order.setStatus(1);
        order.setState(1);
        order.setOrderType(0);
        order.setPayType(2);

        order.setGoodsNumber(1);
        order.setGtype(GtypeEnum.none.getVal());
        order.setXftype(XftypeEnum.buyHuiyuan.getVal());
        order.setType(YXType.common.getVal());
        order.setLinkman(user.getNickName());
        order.setPhone(user.getPhone());
        order.setTradecode(czid == null ? "" : czid.toString());
        order.setOrderNo(StringUtil.getSnNo("X"));
        order.setShortno(orderService.getShortno(ObjectUtil.getMpid()));
        order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
        order.insert();

        OrderGoods og = new OrderGoods();
        og.setOid(order.getId());
        og.setGid(-4l);
        og.setOrderNo(order.getOrderNo());
        og.setPrice(order.getSaleprice());
        og.setSaleprice(order.getSaleprice());
        og.setTotal(order.getTotal());
        og.setNumber(1);
        og.setStatus(1);
        og.setState(1);
        og.setIsDefault(1);
        og.setUid(uid);
        og.setMid(mid);
        og.setMpid(mpid);

        og.setType(YXType.common.getVal());
        og.setOrderType(0);
        og.setGoodsName(order.getGoodsName());
        og.setPic(goods == null ? null : goods.getThumb());
        og.insert();

        AccountFlow af = new AccountFlow();
        af.setRealpay(money);
        af.setAmount(zero);
        af.setDikou(zero);
        af.setTotal(af.getRealpay().add(af.getAmount()).add(af.getDikou()));

        af.setNickname(user != null ? user.getNickName() : null);
        af.setHeadimg(user != null ? user.getAvatarPic() : null);
        af.setPhone(user != null ? user.getPhone() : null);
        Account act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
        if (act == null) {
            act = accountService.initAccount(uid, mid, mpid);
        }
        af.setUid(uid);
        af.setMid(mid);
        af.setMpid(mpid);
        af.setState(1);
        af.setOrigin("");
        af.setIotype(IotypeEnum.input.getVal());//1:入账
        af.setXftype(XftypeEnum.buy.getVal());

        af.setIsConfirm(-1);//未确认
        af.setCreatetime(new Date());
        af.setSn(order.getOrderNo());
        af.setRemark("在线购买会员权益");
        af.setTradetime(new Date());
        af.setCreatetime(new Date());
        af.setLasttotal(act.getTotal());
        af.setLastamount(act.getAmount());
        af.insert();

        MaccountFlow maf = new MaccountFlow();
        maf.setUid(uid);
        maf.setMid(mid);
        maf.setMid(mpid);
        maf.setState(1);
        maf.setIotype(IotypeEnum.input.getVal());//1:入账
        maf.setXftype(XftypeEnum.recharge.getVal());//1:充值
        maf.setAmount(money);
        maf.setMamount(zero);

        maf.setIsConfirm(-1);//未确认
        maf.setSn(af.getSn());
        maf.setRemark("在线购买会员权益");
        maf.setTradetime(new Date());
        maf.setCreatetime(maf.getTradetime());
        maf.insert();

        json.setInfo(orderService.getPaymap(order, false, "在线购买会员权益"));
        return json;
    }

    //恰恰全积分支付
    //用户买单商家收款
    @RequestMapping("/api/order/mshoukuan")
    @ResponseBody
    public Jinfo mshoukuan(@RequestParam("money") BigDecimal money,
                           @RequestParam("remark") String remark,
                           @RequestParam(value = "realpay", required = false) BigDecimal realpay,
                           @RequestParam(value = "jffanbi", required = false) BigDecimal jffanbi,
                           @RequestParam(value = "scene", required = false) String scene,
                           @RequestParam(value = "zke", required = false) BigDecimal zke
    ) {
        Jinfo info = new Jinfo();
        if (money == null || money.doubleValue() <= 0) {
            info.setCode(1);
            info.setMsg("请求参数错误");
            return info;
        }
        if (realpay == null || realpay.doubleValue() <= 0) {
            info.setCode(1);
            info.setMsg("请求参数错误");
            return info;
        }
        if (Strings.isNullOrEmpty(scene)) {
            info.setCode(4);
            info.setMsg("参数错误");
            return info;
        }
        Long mid = ObjectUtil.getMid();
        Long mpid = ObjectUtil.getMpid();
        Long uid = ObjectUtil.getUid();

        String[] scenes = scene.split("_");
        String rkey = Constants.REDIS_APP_USER + mpid + "_" + scenes[0];
        Long touid = Long.valueOf(scenes[0]);

        User ruser = redisService.get(rkey);
        Long storeid = null;
        if (ruser == null) {
            ruser = userService.selectById(scenes[0]);
            storeid = ruser.getSid();
        } else {
            storeid = ruser.getSid();
        }

        if (storeid == null) {
            info.setCode(1);
            info.setMsg("当前码非商户收款码");
            return info;
        }

        MerchantConfig mconfig = redisService.getMconfig();

        BigDecimal zero = new BigDecimal(0);
        Order order = new Order();
        Address address = addressService.selectOne(new EntityWrapper<Address>().eq("uid", uid).eq("is_default", 1));
        if (address != null) {
            order.setLinkman(address.getLinkman());
            order.setPhone(address.getPhone());
            order.setAddress(address.getAddress());
        } else {
            User user = userService.selectById(uid);
            order.setLinkman(user.getNickName());
            order.setPhone(user.getPhone() == null ? "" : user.getPhone());
            order.setAddress(user.getCity() == null ? "" : user.getCity());
        }

        order.setOrderNo(StringUtil.getSnNo("M"));
        order.setShortno(orderService.getShortno(ObjectUtil.getMpid()));
        order.setPayType(PaytypeEnum.weixin.getVal());
        order.setGoodsName(order.getLinkman() + "扫码支付");
        order.setGoodsNumber(1);

        order.setPrices(money);
        order.setTotal(money);
        order.setRealpay(realpay);

        order.setMemberDiscount(zero);// 会员折扣
        // ====待完善
//        order.setDiscount(order.getDeduction().add(order.getMemberDiscount()).add(order.getBikou())
//                .add(order.getJifenDiscount()).add(order.getCouponDiscount()));
        order.setDiscount(zke == null ? zero : zke);//总抵扣
        order.setDeduction(zero);// 会员月抵扣

        order.setFantimeType(mconfig.getFantimeType());
        order.setIsNeedLogistics(0);
        if (realpay.doubleValue() > 0)
            order.setStatus(StatusEnum.forpay.getVal());
        else
            order.setStatus(StatusEnum.forsend.getVal());

        order.setRemark(order.getLinkman() + "扫码支付");

        order.setState(1);

        order.setOrderType(0);
        order.setGtype(GtypeEnum.none.getVal());//产品类型@1：实物产品；2：虚拟产品；3：预约到店服务；4：预约上门服务；6：交纳押金&
        order.setType(YXType.common.getVal());//营销类型@ 0：普通商品； 1：拼团；2：砍价；3：抽奖；4：积分购；5：会员商品
        order.setXftype(XftypeEnum.maidan.getVal());//营销类型@ 0：普通商品； 1：拼团；2：砍价；3：抽奖；4：积分购；5：会员商品

        order.setUid(uid);
        order.setMid(mid);
        order.setSid(storeid);
        Store store = redisService.getStore(order.getSid());
        order.setSname(store == null ? null : store.getName());
        order.setLeagueid(redisService.getLeagueid(storeid));

        if (jffanbi != null && jffanbi.doubleValue() > 0) order.setFanjifen(jffanbi.multiply(realpay));
        order.setMpid(ObjectUtil.getMpid());

        MerchantApp mapp = redisService.getMApp(ObjectUtil.getMpid());
        User user = redisService.getUser();
        //用户消费
        Account act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
        if (act == null) act = orderService.initAccount();
        // 实付 > 0
        if (order.getRealpay().doubleValue() > 0) {
            //用户消费
            //余额支付,默认不赠送积分
            //商家收款，确认通知里处理
            AccountFlow af = new AccountFlow();

            af.setTradetime(new Date());
            af.setRemark("扫码支付给商家");// 1:微信 2:余额 3:币 9:线下支付
            af.setState(1);
            af.setMid(mid);
            af.setMpid(ObjectUtil.getMpid());
            af.setUid(uid);

            af.setNickname(user != null ? user.getNickName() : null);
            af.setHeadimg(user != null ? user.getAvatarPic() : null);
            af.setPhone(user != null ? user.getPhone() : null);

            af.setCreatetime(new Date());
            af.setSn(order.getOrderNo());

            af.setTotal(order.getTotal());    //订单金额
            af.setRealpay(order.getRealpay());//实付金额
            af.setAmount(zero);               //会员余额抵扣
            af.setDikou(order.getDiscount()); //其他抵扣

            af.setIsConfirm(-1);              //线下支付
            af.setIotype(IotypeEnum.output.getVal());
            af.setXftype(XftypeEnum.maidan.getVal());// 余额抵扣【带抵扣的消费】
            af.setSid(storeid);
            af.setRemark(remark);
            af.setLasttotal(act.getTotal());
            af.setLastamount(act.getAmount());
            af.insert();

            af.setId(null);
            af.setRemark(mapp.getName() + "渠道扫码收款");// 1:微信 2:余额 3:币 9:线下支付
            af.setIotype(IotypeEnum.input.getVal());
            af.setXftype(XftypeEnum.mshoukuan.getVal());// 余额抵扣【带抵扣的消费】
            User touser = userService.selectById(touid);
            Account toact = accountService.selectOne(new EntityWrapper<Account>().eq("uid", touid));
            if (toact == null) {
                toact = accountService.initAccount(touid, mid, mpid);
            }
            af.setUid(touser.getId());
            af.setHeadimg(touser.getAvatarPic());
            af.setPhone(touser.getPhone());
            af.setNickname(touser.getNickName());
            af.setLasttotal(toact.getTotal());
            af.setLastamount(toact.getAmount());
            af.insert();

            //平台收款，确认通知里处理
            MaccountFlow maf = new MaccountFlow();
            maf.setAmount(order.getRealpay());// 实付金额
            maf.setMamount(order.getDiscount());// 赠送金额（营销金额）

            maf.setUid(order.getUid());
            maf.setMid(order.getMid());
            maf.setMpid(order.getMpid());
            maf.setCreatetime(new Date());
            maf.setTradetime(new Date());
            maf.setState(1);//未确认
            maf.setIsConfirm(-1);//未确认

            maf.setIotype(IotypeEnum.input.getVal());//1:入账账
            //对于平台来说，该笔支付订单是线下买单buy
            maf.setXftype(XftypeEnum.buy.getVal());

            maf.setRemark(af.getRemark() + "【代收款】");
            maf.setSn(order.getOrderNo());
            maf.insert();
        }
        order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
        order.insert();
        info.setInfo(getShoukuanMap(order, "在线支付"));

        return info;
    }

    /**
     * 微信支付回调
     */
    @RequestMapping(value = "/pay/notify", produces = "application/xml; charset=UTF-8")
    @ResponseBody
    public void notify(HttpServletRequest request, HttpServletResponse response) throws Exception {

        BufferedReader reader = request.getReader();
        StringBuffer sb = new StringBuffer();
        String line = "";
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        logger.debug(">>>>>>>>>>>>>>>>>>/pay/notify =" + sb.toString());

        Map<String, String> map = XMLUtil.doXMLParse(sb.toString());

        String return_code = map.get("return_code");
//        //客户订单id(虚拟支付单号)
        String sn = map.get("out_trade_no");
//        //微信支付订单号（流水号）
        String transaction_id = map.get("transaction_id");
        String time_end = map.get("time_end");
//        //todo 修改订单对应的状态
//        //商户处理后同步返回给微信参数
//        Order order = orderService.selectOne(new EntityWrapper<Order>().eq("order_no", sn));
//        order.setStatus(order.getGtype() == 1 ? 2 : 3);
//        order.setTransactionId(transaction_id);
//        payConfirm(order);
        AkkaServer.system.actorOf(Props.create(OrderActor.class))
                .tell(Constants.AKKA_MSG_ORDER_CONFIRM + "@" + sn + "@" + transaction_id + "@" + time_end, ActorRef.noSender());

        response.getWriter().print("<xml><return_code><![CDATA[" + return_code + "]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
    }

    /**
     * 微信支付(会员充值)回调
     */
    @RequestMapping(value = "/recharge/notify", produces = "application/xml; charset=UTF-8")
    @ResponseBody
    public void rechargeNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {

        BufferedReader reader = request.getReader();
        StringBuffer sb = new StringBuffer();
        String line = "";
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>/recharge/notify =" + sb.toString());

        Map<String, String> map = XMLUtil.doXMLParse(sb.toString());

        String return_code = map.get("return_code");
        //客户订单id(虚拟支付单号)
        String sn = map.get("out_trade_no");
        //微信支付订单号（流水号）
        String transaction_id = map.get("transaction_id");
        String time_end = map.get("time_end");

        response.getWriter().print("<xml><return_code><![CDATA[" + return_code + "]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");

        //商户处理后同步返回给微信参数
//        rechargeConfirm(sn);
        AkkaServer.system.actorOf(Props.create(OrderActor.class))
                .tell(Constants.AKKA_MSG_RECHARGE_CONFIRM + "@" + sn + "@" + transaction_id + "@" + time_end, ActorRef.noSender());
    }


    /*
     * 派单确认
     */
    @RequestMapping("/api/order/pdconfirm")
    @ResponseBody
    public Jinfo confirmPyqOrder(@RequestParam("orderNo") String orderNo) {
        Jinfo json = new Jinfo();
        if (Strings.isNullOrEmpty(orderNo)) {
            json.setCode(1);
            json.setMsg("parameter error");
            return json;
        }
        Order order = orderService.selectOne(new EntityWrapper<Order>().eq("order_no", orderNo));
        qnpay.updateOrderStatus(order, StatusEnum.commenting.getVal());

        // 客户点击确认收货，入账通知
        AkkaServer.system.actorOf(Props.create(OrderActor.class))
                .tell(Constants.AKKA_MSG_PAIDAN_RUZHANG + "@" + order.getOrderNo() + "@" + FantimeType.after7days.getVal(), ActorRef.noSender());
        return json;
    }


    // 处理商家收款逻辑 >0 逻辑
    private SortedMap<String, Object> getShoukuanMap(Order order, String title) {
        String prepay_id = null;
        SortedMap<String, Object> smap = new TreeMap<String, Object>();
        long mid = order.getMid();
        String uid = order.getUid().toString();
        MerchantApp mapp = redisService.getMApp(order.getMpid());
        String appid = mapp.getAppid();

        //时间戳
        String nonce_str = StringUtil.getGUID().substring(0, 16);
        //订单编号
        String orderNo = order.getOrderNo();
        User user = redisService.getUser();

        // 生成支付相关字段
        // 1.得到openid
        String openid = user.getOpenid();// 替换redis

        logger.debug(">>>order.getRealpay()=" + order.getRealpay());
        if (order.getRealpay() == null) order.setRealpay(new BigDecimal(0));

        BigDecimal totalfee = order.getRealpay().multiply(new BigDecimal("100"));

        //得到小程序传过来的价格，注意这里的价格必须为整数，1代表1分，所以传过来的值必须*100；
        int fee = totalfee.intValue();

        if (Strings.isNullOrEmpty(title)) title = "在线支付购买";//订单标题

        SortedMap<String, Object> params = new TreeMap<String, Object>();

        String expireTime = DateUtil.getOrderExpireTime(30 * 60 * 1000l);// 半个小时自动失效
        if (order.getGtype() == 5) {
            expireTime = DateUtil.getOrderExpireTime(5 * 60 * 1000l);
        }

        //新增服务商模式支付
        if(!Strings.isNullOrEmpty(mapp.getServappid())&&!Strings.isNullOrEmpty(mapp.getServmchid())){
            params.put("appid", mapp.getServappid());
            params.put("mch_id", mapp.getServmchid());
            params.put("openid", "");//openid

            params.put("sub_appid", appid);
            params.put("sub_mch_id", mapp.getMchid());
            params.put("sub_openid", openid);//openid

        } else {
            params.put("appid", appid);
            params.put("mch_id", mapp.getMchid());
            params.put("openid", openid);//openid
        }
        params.put("nonce_str", nonce_str);//时间戳
        params.put("body", title);//支付主体
        params.put("out_trade_no", orderNo);//编号
        params.put("total_fee", fee);//价格
        //  params.put("spbill_create_ip", getIp2(request));这里之前加了ip，但是总是获取sign失败，原因不明，之后就注释掉了
        //  params.put("spbill_create_ip", req.getRemoteAddr()); //这里之前加了ip，但是总是获取sign失败，原因不明，之后就注释掉了
        String notifyUrl = Constants.ROOT_URL + "/pay/notify";
        logger.debug("==========notifyUrl=" + notifyUrl);
        params.put("notify_url", notifyUrl); //支付返回地址，不用纠结这个东西，我就是随便写了一个接口，内容什么都没有
        params.put("trade_type", "JSAPI");//这个api有，固定的

        //获取sign
        String sign = PayCommonUtil.createSign("UTF-8", params, mapp.getPaykey());//最后这个是自己设置的32位密钥
        params.put("sign", sign);

        //转成XML
        logger.debug("--------------------------------------params=" + params);
        String requestXML = PayCommonUtil.getRequestXml(params);

        //得到含有prepay_id的XML
//        String resXml = HttpUtil.sendPost(Constants.WX_URL_UNIFIEDORDER, requestXML);
        String resXml = HttpUtil.postData(Constants.WX_URL_UNIFIEDORDER, requestXML);
        logger.debug(">>>requestXML");
        logger.debug(resXml);

        //解析XML存入Map
        Map map = null;
        try {
            map = XMLUtil.doXMLParse(resXml);
        } catch (JDOMException | IOException e) {
            logger.error(">>>doXMLParse error", e);
            smap.put("code", 1);
            smap.put("msg", "支付异常");
            return smap;
        }
        if (map.get("result_code").equals("FAIL")) {
            smap.put("code", 1);
            smap.put("msg", map.get("err_code_des"));
            return smap;
        }
        prepay_id = (String) map.get("prepay_id");

        // 更新订单
        Order uorder = new Order();
        uorder.setPrepayid(prepay_id);
        uorder.setId(order.getId());
        uorder.updateById();

        smap.put("appId", appid);//！！！注意，这里是appId,上面是appid，真怀疑写这个东西的人。。。
        smap.put("nonceStr", nonce_str);//时间戳
        smap.put("package", "prepay_id=" + prepay_id);//必须把package写成 "prepay_id="+prepay_id这种形式
        smap.put("signType", "MD5");//paySign加密
        smap.put("timeStamp", (System.currentTimeMillis() / 1000) + "");

        //得到paySign
        String paySign = PayCommonUtil.createSign("UTF-8", smap, mapp.getPaykey());
        smap.put("paySign", paySign);
        smap.put("oid", order.getId());//paySign加密
        return smap;
    }

    /*
     * 押金提现申请列表
     */
    @RequestMapping("/api/order/yajinshlist")
    @ResponseBody
    public Jinfo yajinshlist() {
        Jinfo info = new Jinfo();

        List<Order> list = orderService.selectList(new EntityWrapper<Order>()
                .setSqlSelect("id,is_refund,realpay,headimg,createtime")
                .eq("xftype", XftypeEnum.jyajin.getVal())
                .eq("mpid", ObjectUtil.getMpid())
                .ge("is_refund", 0)
                .orderBy("id", false)
        );
        info.setInfo(list);
        return info;
    }

    /*
     * 押金提现申请
     */
    @RequestMapping("/api/order/yjshenhe")
    @ResponseBody
    public Jinfo yjshenhe(Long id, Integer state) {
        Jinfo info = new Jinfo();

        Order order = orderService.selectById(id);
        if (state == null || (state != 1 && state != -1)) {
            info.setCode(1);
            info.setMsg("参数有误");
            return info;
        }

        if (order == null) {
            info.setCode(4);
            info.setMsg("该押金记录不存在");
            return info;
        }

        OrderRefund or = orderRefundService.selectOne(new EntityWrapper<OrderRefund>()
                .eq("oid", id)
                .eq("refund_no", order.getRefundNo())
        );
        if (or == null) {
            info.setCode(4);
            info.setMsg("该押金申请记录不存在");
            return info;
        }
        Boolean flag = false;
        Long uid = order.getUid();
        User user = userService.selectById(uid);
        Map map = new HashMap<String, String>();

        order.setModifytime(new Date());
        order.setModifier(ObjectUtil.getUid());

        if (state == 1) {
            //审核通过

            // 生成订单取消申请
            map = qnpay.getRefundmap(order.getMid(), ObjectUtil.getAppid(), order.getOrderNo(), order.getRefundNo(),
                    order.getRealpay(), order.getRealpay(), Constants.REFUND_SOURCE_UNSETTLED_FUNDS);

            if (map == null || !map.containsKey("result_code") || !map.get("result_code").equals("SUCCESS")) {
                map.put("code", 1);
                info.setCode(1);
                info.setMsg("在线退款失败,请后台处理");
                return info;
//                or.setStatus(7);//失败
//                or.updateById();
//
//                order.setIsRefund(-1);
//                order.setRefundNo(null);
//                order.updateById();

            } else {
                order.setIsRefund(1);
                order.setStatus(0);
                order.updateById();

                AccountFlow af = new AccountFlow();
                af.setRealpay(order.getRealpay());
                af.setDikou(new BigDecimal(0));
                af.setAmount(af.getDikou());

                af.setNickname(user != null ? user.getNickName() : null);
                af.setHeadimg(user != null ? user.getAvatarPic() : null);
                af.setPhone(user != null ? user.getPhone() : null);

                af.setTotal(af.getRealpay().add(af.getAmount()).add(af.getDikou()));

                af.setRemark("押金退回");
                af.setIsConfirm(-1);
                af.setState(1);
                af.setMpid(ObjectUtil.getMpid());
                af.setUid(uid);
                Account act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
                if (act == null) {
                    act = accountService.initAccount(uid, user.getMid(), user.getMpid());
                }

                af.setMid(ObjectUtil.getMid());
                af.setTradetime(new Date());
                af.setCreatetime(new Date());
                af.setIotype(IotypeEnum.output.getVal());
                af.setXftype(XftypeEnum.tyajin.getVal());
                af.setSn(order.getRefundNo());
                af.setLasttotal(act.getTotal());
                af.setLastamount(act.getAmount());
                af.insert();

                Account naccount = new Account();

                while (af != null && !flag) {

                    af.setIsConfirm(1);
                    af.setRuzhang(1);
                    af.setConfirmDate(new Date());

                    Long version = act.getVersion();
                    BigDecimal total = act.getTotal();
                    BigDecimal yajin = act.getYajin();

                    naccount.setTotal(total.subtract(af.getRealpay()));
                    naccount.setYajin(yajin.subtract(af.getRealpay()));

                    naccount.setModifytime(new Date());
                    naccount.setModifier(uid);
                    naccount.setVersion(version + 1);

                    flag = accountService.update(naccount, new EntityWrapper<Account>().eq("uid", uid).eq("version", version));
                    if (flag) af.updateById();
                    act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
                }

                //******* 写入[商家退款流水] *******
                MaccountFlow omaf = maccountFlowService.selectOne(new EntityWrapper<MaccountFlow>().eq("sn", order.getOrderNo()));

                MaccountFlow maf = new MaccountFlow();
                maf.setAmount(omaf.getAmount());
                maf.setMamount(omaf.getMamount());

                maf.setState(1);
                maf.setIsConfirm(-1);
                maf.setCreatetime(new Date());
                maf.setTradetime(new Date());
                maf.setIotype(IotypeEnum.output.getVal());
                maf.setXftype(XftypeEnum.refund.getVal());
                maf.setSn(af.getSn());
                maf.setMid(order.getMid());
                maf.setMpid(order.getMpid());
                maf.setUid(uid);
                maf.insert();

                flag = false;
                if (maf != null) {
                    flag = false;
                    Maccount maccount = new Maccount();//押金提现申请
                    while (!flag) {
                        Maccount ma = maccountService.selectOne(new EntityWrapper<Maccount>().eq("mid", order.getMid()));

                        maf.setIsConfirm(1);
                        maf.setLasttotal(ma.getTotal());
                        maf.setConfirmDate(new Date());

                        Long version = ma.getVersion();
                        BigDecimal total = ma.getTotal();
                        BigDecimal amount = ma.getAmount();
                        BigDecimal sale = ma.getSaleAmount();

                        maccount.setTotal(total.subtract(maf.getAmount()));      //总金额
                        maccount.setSaleAmount(sale.subtract(maf.getAmount()));      //累计销售额度
                        maccount.setAmount(amount.subtract(maf.getAmount()));      //可用余额

                        maccount.setModifytime(new Date());
                        maccount.setModifier(uid);
                        maccount.setVersion(version + 1);

                        maf.setIsConfirm(1);
                        maf.setLasttotal(ma.getTotal());
                        maf.setConfirmDate(new Date());
                        maf.setModifytime(new Date());

                        flag = maccountService.update(maccount, new EntityWrapper<Maccount>()
                                .eq("id", ma.getId())
                                .eq("version", version));
                        if (flag) maf.insertOrUpdate();
                    }
                }
            }
        } else {
            or.setStatus(7);// 提现失败
            or.updateById();

            //审核拒绝
            order.setIsRefund(-1);
            order.setRefundNo(null);
            order.updateById();
        }

        //更新用户信息
        if (state == 1) {
            User nuser = new User();
            nuser.setId(order.getUid());
            nuser.setIsStaff(-1);
            nuser.updateById();
            redisService.delUser(order.getUid());
        }
        return info;
    }

    //商家买单接口，根据优惠券来分配奖励《平台+盟主版接口》
    //quanid+quankou可以为空
    //realpay可以为0
    @RequestMapping("/api/order/smdan")
    @ResponseBody
    public Jinfo smdan(@RequestParam("money") BigDecimal money,
                       @RequestParam("remark") String remark,
                       @RequestParam(value = "realpay", required = false) BigDecimal realpay,
                       @RequestParam(value = "sid", required = false) Long sid,
                       @RequestParam(value = "quanid", required = false) Long quanid,
                       @RequestParam(value = "quankou", required = false) BigDecimal quankou) {
        logger.debug("--------------------------------------order/smdan come 000");

        Jinfo json = new Jinfo();

        if (money == null || money.doubleValue() <= 0) {
            json.setCode(1);
            json.setMsg("请求参数错误");
            return json;
        }
        if (sid == null || sid <= 0) {
            json.setCode(1);
            json.setMsg("请求参数错误");
            return json;
        }

        Long mid = ObjectUtil.getMid();
        Long mpid = ObjectUtil.getMpid();
        Long uid = ObjectUtil.getUid();
        User ruser = redisService.getUser();
        logger.debug("--------------------------------------order/smdan come 1111");

        MerchantConfig mconfig = redisService.getMconfig();
        logger.debug("--------------------------------------order/mdan come 222");

        BigDecimal zero = new BigDecimal(0);
        Order order = new Order();
        Address address = addressService.selectOne(new EntityWrapper<Address>().eq("uid", uid).eq("is_default", 1));
        if (address != null) {
            order.setLinkman(address.getLinkman());
            order.setPhone(address.getPhone());
            order.setAddress(address.getAddress());
        } else {
            order.setLinkman(ruser.getNickName());
            order.setPhone(ruser.getPhone() == null ? "" : ruser.getPhone());
            order.setAddress(ruser.getCity() == null ? "" : ruser.getCity());
        }
        order.setHeadimg(ruser.getAvatarPic());

        order.setOrderNo(StringUtil.getSnNo("M"));
        order.setShortno(orderService.getShortno(ObjectUtil.getMpid()));
        order.setPayType(PaytypeEnum.weixin.getVal());
        order.setGoodsName(order.getLinkman() + "商家优惠买单");
        order.setGoodsNumber(1);

        order.setPrices(money);
        order.setTotal(money);
        order.setRealpay(realpay);

        order.setDeduction(zero);    // 余额折扣
        order.setMemberDiscount(zero);// 会员折扣
        order.setCouponDiscount(quankou);
        order.setCouponId(quanid);

        order.setBie(0);//虚拟币跟人民币默认1：1关系
        order.setBikou(zero);
        order.setJifenDiscount(zero);

        //积分抵扣额*积分倍率
        order.setJifen(zero);
        // ====待完善
        order.setDiscount(order.getCouponDiscount());
        logger.debug("--------------------------------------order/mdan come 333");

        order.setFantimeType(FantimeType.payok.getVal());
        order.setRealpay(realpay);
        order.setIsNeedLogistics(0);

        if (realpay.doubleValue() > 0)
            order.setStatus(StatusEnum.forpay.getVal());
        else
            order.setStatus(StatusEnum.forsend.getVal());

        order.setState(1);

        order.setGtype(GtypeEnum.none.getVal());//既有实物也有服务+虚实订单
        order.setOrderType(1);
        order.setGtype(GtypeEnum.none.getVal());//产品类型@1：实物产品；2：虚拟产品；3：预约到店服务；4：预约上门服务；6：交纳押金&
        order.setType(YXType.common.getVal());//营销类型@ 0：普通商品； 1：拼团；2：砍价；3：抽奖；4：积分购；5：会员商品
        order.setXftype(XftypeEnum.smaidan.getVal());//消费类型:优惠券买单

        order.setUid(uid);
        order.setMid(mid);
        order.setMpid(mpid);
        order.setSid(sid);
        Store store = redisService.getStore(order.getSid());
        order.setSname(store == null ? null : store.getName());
        order.setRemark(remark);
        Long menguid = redisService.getLeagueAdminuser(sid);
        Long lmid = redisService.getLeagueid(sid);
        order.setLeagueid(lmid);

        //计算分享者
        // ============实时消券============
        Coupon coupon = null;
        CouponTpl couponTpl = null;
        if (quankou != null && quanid != null) {
            coupon = couponService.selectById(quanid);
            if (coupon != null) couponTpl = couponTplService.selectById(coupon.getTplid());
            //如果realpay>支付成功之后再核销
            //否则直接核销
            //对于实付金额小于等于0，没有佣金
            if (realpay != null && realpay.doubleValue() <= 0 && coupon != null) {
                coupon.setIsUsed(1);
                coupon.setUsetime(new Date());
                coupon.setIsUnused(0);
                coupon.updateById();
                order.setFxmode(null);
            } else {
                //有赠送人+支持分销
                if (coupon.getZfuid() != null && couponTpl.getFenxiao().intValue() == Qfxtype.fenxiao.getVal()) {
                    order.setFanuid(coupon.getZfuid());

                } else if (coupon.getZfuid() != null && couponTpl.getFenxiao().intValue() == Qfxtype.tuijian.getVal()) {
                    //走分享奖励模式，该行为在领券动作触发
                } else if (coupon.getZfuid() != null && couponTpl.getFenxiao().intValue() == Qfxtype.fenxiao.getVal()) {
                    //走分分销模式，该行为af.insert()做记录
                }

                if (couponTpl != null) {
                    order.setFxmode(couponTpl.getFenxiao() == null || couponTpl.getFenxiao() == 0 ? null : Fxmode.common.getVal());
                }

            }
        }
        logger.debug("--------------------------------------order/mdan come 444");

        User user = redisService.getUser();

        // 实付 > 0
        if (order.getRealpay().doubleValue() > 0) {
            //用户优惠买单
            //商家收款，支付确认通知里处理
            AccountFlow af = new AccountFlow();

            //买单用户
            af.setTradetime(new Date());
            af.setRemark(store.getName() + "优惠买单收款");// 1:微信 2:余额 3:币 9:线下支付
            af.setState(1);
            af.setMid(mid);
            af.setMpid(mpid);
            af.setSid(sid);
            af.setLeagueid(lmid);
            af.setUid(uid);
            Account act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
            if (act == null) {
                act = accountService.initAccount(uid, mid, mpid);
            }
            af.setNickname(user != null ? user.getNickName() : null);
            af.setHeadimg(user != null ? user.getAvatarPic() : null);
            af.setPhone(user != null ? user.getPhone() : order.getPhone());

            af.setCreatetime(new Date());
            af.setSn(order.getOrderNo());

            af.setTotal(order.getTotal());    //订单金额
            af.setRealpay(order.getRealpay());//实付金额
            af.setAmount(zero);               //会员余额抵扣
            af.setDikou(order.getDiscount()); //其他抵扣

            af.setIsConfirm(-1);
            af.setFantimeType(FantimeType.payok.getVal());
            af.setIotype(IotypeEnum.output.getVal());
            af.setXftype(XftypeEnum.maidan.getVal());// 余额抵扣【带抵扣的消费】
            af.setXftypename(XftypeEnum.maidan.getName());// 余额抵扣【带抵扣的消费】
            af.setLasttotal(act.getTotal());
            af.setLastamount(act.getAmount());
            af.insert();

            //=========分享者=========
            boolean share = false;

            BigDecimal one = new BigDecimal(1);
            Mdpay entity = new Mdpay();
            entity.setSid(sid);
            Mdpay mdpay = mdpayMapper.selectOne(entity);
            if (mdpay == null) {
                mdpay = new Mdpay();
                mdpay.setSid(sid);
                mdpay.setMpid(order.getMpid());
                mdpay.setCreatetime(new Date());
                mdpay.setLeagueid(order.getLeagueid());

                mdpay.setState(1);
                mdpay.setFangshua(-1);

                mdpay.setPaymch(new BigDecimal(0.7));//商家默认0.7
                mdpay.setPayplat(new BigDecimal(0.1));//平台默认0.1

                mdpay.setPayshare(new BigDecimal(0.1));//分享者默认0.1
                mdpay.setPaymeng(new BigDecimal(0.1));//默认0.1
                mdpay.insert();
            }
            logger.debug("--------------------------------------order/mdan come mdpay=" + JSON.toJSONString(mdpay));
            if (order.getFanuid() == null) {
                mdpay.setPayshare(zero);
                if (lmid == null) {
                    mdpay.setPaymeng(zero);
                    mdpay.setPayplat(one.subtract(mdpay.getPaymch()));
                } else {
                    mdpay.setPaymeng(one.subtract(mdpay.getPaymch()).subtract(mdpay.getPayplat()));//利他模式之【利代理】
                }
            } else {
                if (lmid == null) {
                    mdpay.setPaymeng(zero);
                    mdpay.setPayplat(one.subtract(mdpay.getPaymch()).subtract(mdpay.getPayshare()));
                } else {
                }
            }

            //=========商家=========
            BigDecimal ptfan = order.getRealpay().multiply(mdpay.getPayplat());//平台固定收益
            BigDecimal minprice = order.getRealpay().multiply(mdpay.getPaymch());
            BigDecimal lmfan = order.getRealpay().multiply(mdpay.getPaymeng());
            BigDecimal sharefan = order.getRealpay().multiply(mdpay.getPayshare());

            order.setPtfan(ptfan);
            order.setMinprice(minprice);
            order.setLmfan(lmfan);
            order.setSharefan(sharefan);

            logger.debug("--------------------------------------order/mdan come order.getFanuid()=" + order.getFanuid());
            logger.debug("--------------------------------------order/mdan come order.getCouponId()=" + order.getCouponId());

            //=========盟主=========
            logger.debug("--------------------------------------order/mdan come menguid=" + menguid);

            //=========平台=========
            //平台收款，确认通知里处理
            MaccountFlow maf = new MaccountFlow();
            maf.setAmount(order.getRealpay());// 实付金额
            maf.setMamount(order.getDiscount());// 赠送金额（营销金额）

            maf.setUid(order.getUid());
            maf.setMid(order.getMid());
            maf.setMpid(order.getMpid());
            maf.setCreatetime(new Date());
            maf.setTradetime(new Date());
            maf.setState(1);//未确认
            maf.setIsConfirm(-1);//未确认

            maf.setIotype(IotypeEnum.input.getVal());//1:入账账
            //对于平台来说，该笔订单属于线下消费
            maf.setXftype(XftypeEnum.buy.getVal());

            maf.setRemark(store.getName() + "线下消费优惠买单订单");
            maf.setSn(order.getOrderNo());
            maf.insert();
        }

        //处理券分销分佣，凡在支付之后
        //处理券分销分佣的钱只针对实际支付金额来计算

        order.setLeagueid(lmid);
        order.setExpire(0);//如放弃支付，该笔交易默认立即失效
        order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
        order.insert();
        logger.debug("--------------------------------------order/mdan come 999");

        if (order.getRealpay().doubleValue() > 0)
            json.setInfo(getShoukuanMap(order, "在线支付"));

        return json;
    }

    //仟牛通开通会员买单接口，根据优惠券来分配奖励
    @RequestMapping("/api/order/nhykaitong")
    @ResponseBody
    public Jinfo nhykaitong(
            @RequestParam("money") BigDecimal money,
            @RequestParam("type") String type,
            @RequestParam("level") Integer level,
            @RequestParam(value = "scene", required = false) String scene,
            @RequestParam(value = "ori", required = false) String ori,
            @RequestParam(value = "expire", required = false) Integer expire) {
        logger.debug("--------------------------------------order/ncdkaitong come 000");

        Jinfo json = new Jinfo();

        if (money == null || money.doubleValue() <= 0) {
            json.setCode(1);
            json.setMsg("请求参数错误");
            return json;
        }

        Long mid = ObjectUtil.getMid();
        Long mpid = ObjectUtil.getMainmpid() == null ? ObjectUtil.getMpid() : ObjectUtil.getMainmpid();
        Long uid = ObjectUtil.getUid();
        if (uid == null) {
            json.setCode(1);
            json.setIsphone(0);
            json.setMsg("授权登录之后在操作");
            return json;
        }
        Long sid = ObjectUtil.getSid();
        logger.debug("--------------------------------------order/smdan come sid=" + sid);

        BigDecimal zero = new BigDecimal(0);
        Order order = new Order();

        String tname = level == 1 ? "VIP版" : level == 2 ? "旗舰版" : "旗舰版";

        Address address = addressService.selectOne(new EntityWrapper<Address>().eq("uid", uid).eq("is_default", 1));
        if (address != null) {
            order.setLinkman(address.getLinkman());
            order.setPhone(address.getPhone());
            order.setAddress(address.getAddress());
        } else {
            User user = userService.selectById(uid);
            order.setLinkman(user.getNickName());
            order.setPhone(user.getPhone() == null ? "" : user.getPhone());
            order.setAddress(user.getCity() == null ? "" : user.getCity());
        }

        order.setOrderNo(StringUtil.getSnNo("M"));
        order.setShortno(orderService.getShortno(mpid));
        order.setPayType(PaytypeEnum.weixin.getVal());
        order.setGoodsName(order.getLinkman() + "付费开通牛财多" + tname);
        order.setGoodsNumber(1);

        order.setPrices(money);
        order.setTotal(money);
        order.setRealpay(money);

        order.setDeduction(zero);    // 余额折扣
        order.setMemberDiscount(zero);// 会员折扣
        order.setCouponDiscount(zero);
        order.setCouponId(null);
        order.setBie(0);//虚拟币跟人民币默认1：1关系
        order.setBikou(zero);
        order.setJifenDiscount(zero);

        //积分抵扣额*积分倍率
        order.setJifen(zero);
        // ====待完善
        order.setDiscount(order.getCouponDiscount());
        logger.debug("--------------------------------------order/mdan come 333");

        order.setFantimeType(FantimeType.payok.getVal());
        order.setRealpay(money);
        order.setIsNeedLogistics(0);
        order.setStatus(StatusEnum.forpay.getVal());

        order.setState(1);

        order.setOrderType(1);
        order.setGtype(GtypeEnum.none.getVal());//产品类型@1：实物产品；2：虚拟产品；3：预约到店服务；4：预约上门服务；6：交纳押金&
        order.setType(YXType.common.getVal());//营销类型@ 0：普通商品； 1：拼团；2：砍价；3：抽奖；4：积分购；5：会员商品
        order.setXftype(XftypeEnum.shymaidan.getVal());//消费类型特殊会员买单
        order.setFxmode(Fxmode.common.getVal());//普通分销模型

        order.setUid(uid);
        order.setMid(mid);
        order.setMpid(mpid);
        order.setSid(sid);

        Store store = redisService.getStore(order.getSid());
        order.setSname(store == null ? null : store.getName());
        order.setTradecode(type + "_" + level + "_" + expire);//记录类型和购买期限

        if (sid != null) order.setLeagueid(redisService.getLeagueid(sid));
        //订单来源
        if (!Strings.isNullOrEmpty(scene) || !Strings.isNullOrEmpty(ori)) {
            ori = scene + "@" + ori;
            order.setOri(ori);
            order.setFanuid(ObjectUtil.orderFanuid(ori));
        }

        User user = redisService.getUser();

        // 实付 > 0
        AccountFlow af = new AccountFlow();

        //买单用户
        af.setTradetime(new Date());
        af.setRemark(order.getGoodsName());// 1:微信 2:余额 3:币 9:线下支付
        af.setState(1);
        af.setMid(mid);
        af.setMpid(mpid);
        af.setSid(sid);
        af.setUid(uid);
        Account act2 = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
        if (act2 == null) {
            act2 = accountService.initAccount(uid, af.getMid(), af.getMpid());
        }

        af.setNickname(user != null ? user.getNickName() : null);
        af.setHeadimg(user != null ? user.getAvatarPic() : null);
        af.setPhone(user != null ? user.getPhone() : null);

        af.setCreatetime(new Date());
        af.setSn(order.getOrderNo());

        af.setTotal(order.getTotal());    //订单金额
        af.setRealpay(order.getRealpay());//实付金额
        af.setAmount(zero);               //会员余额抵扣
        af.setDikou(order.getDiscount()); //其他抵扣

        af.setIsConfirm(-1);
        af.setIotype(IotypeEnum.output.getVal());
        af.setXftype(XftypeEnum.buy.getVal());// 余额抵扣【带抵扣的消费】
        af.setXftypename(XftypeEnum.buy.getName());// 余额抵扣【带抵扣的消费】
        af.setLasttotal(act2.getTotal());
        af.setLastamount(act2.getAmount());
        af.insert();

        //如果是商家推荐，商家得30%，盟主得30%，平台得40%
        //如果是盟主推荐，商家得0%，盟主得60%，平台得40%
        //自助开通，非转发开通
        if (sid != null && order.getFanuid() == null) {
            Mdpay mdpay = mdpayMapper.selectById(sid);
            if (mdpay == null) {
                mdpay = new Mdpay();
                mdpay.setSid(sid);
                mdpay.setMpid(order.getMpid());
                mdpay.setCreatetime(new Date());
                mdpay.setLeagueid(order.getLeagueid());
                mdpay.setPaymch(new BigDecimal(0.7));//商家默认0.7
                mdpay.setPayplat(new BigDecimal(0.1));//平台默认0.1
                mdpay.setPayshare(new BigDecimal(0.1));//分享者默认0.1
                mdpay.setPaymeng(new BigDecimal(0.1));//默认0.1
                mdpay.insert();
            }
            logger.debug("--------------------------------------order/mdan come mdpay=" + JSON.toJSONString(mdpay));

            //=========盟主=========
            Long menguid = redisService.getLeagueAdminuser(sid);
            logger.debug("--------------------------------------order/mdan come menguid=" + menguid);

            if (menguid != null) {
                //优先返盟主
                order.setFanuid(null);
                order.setLmfan(money.multiply(new BigDecimal(0.3)));
                order.setPtfan(money.multiply(new BigDecimal(0.7)));
                order.setSharefan(null);

                af.setId(null);
                //对于盟主来说，该笔收款是代理收款
                af.setIotype(IotypeEnum.input.getVal());
                af.setXftype(XftypeEnum.tuijianfan.getVal());
                af.setXftypename(XftypeEnum.tuijianfan.getName());
                af.setAmount(order.getLmfan());//实付金额

                af.setTotal(af.getAmount());//订单金额
                af.setRealpay(zero);//订单金额
                af.setDikou(zero);//订单金额

                User menguser = userService.selectById(menguid);
                Account act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", menguid));
                if (act == null) {
                    act = accountService.initAccount(menguser.getId(), menguser.getMid(), menguser.getMpid());
                }
                af.setUid(menguser.getId());
                af.setHeadimg(menguser.getAvatarPic());
                af.setPhone(menguser.getPhone());
                af.setNickname(menguser.getNickName());
                af.setLasttotal(act.getTotal());
                af.setLastamount(act.getAmount());
                af.insert();
            }

        } else if (order.getFanuid() != null) {

            //如果是商家推荐，商家得30%，盟主得30%，平台得40%
            //如果是盟主推荐，商家得0%，盟主得60%，平台得40%
            User fanuser = userService.selectById(order.getFanuid());
            //只有商家或者盟主推荐商家才有推荐佣金
            if (fanuser != null && fanuser.getSid() != null && fanuser.getSlevel() != null) {

                //=========盟主=========
                Long menguid = redisService.getLeagueAdminuser(fanuser.getSid());
                logger.debug("--------------------------------------order/mdan come menguid=" + menguid);
                //体验商家会员，10%提成，正式会员30%提成
                order.setSharefan(fanuser.getSlevel() == 0 ? new BigDecimal(0.1).multiply(money) : new BigDecimal(0.3).multiply(money));

                if (menguid != null) {
                    order.setLmfan(money.multiply(new BigDecimal(0.3)));
                } else {
                    order.setLmfan(money.multiply(new BigDecimal(0)));
                }
                order.setPtfan(money.subtract(order.getSharefan()).subtract(order.getLmfan()));

                if (menguid != null) {
                    //返盟主
                    af.setId(null);
                    //对于盟主来说，该笔收款是代理收款
                    af.setIotype(IotypeEnum.input.getVal());
                    af.setXftype(XftypeEnum.tuijianfan.getVal());
                    af.setXftypename(XftypeEnum.tuijianfan.getName());
                    af.setAmount(order.getLmfan());//实付金额

                    af.setTotal(af.getAmount());//订单金额
                    af.setRealpay(zero);//订单金额
                    af.setDikou(zero);//订单金额

                    User menguser = userService.selectById(menguid);
                    Account act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", menguid));
                    if (act == null) {
                        act = accountService.initAccount(menguser.getId(), menguser.getMid(), menguser.getMpid());
                    }
                    af.setUid(menguser.getId());
                    af.setHeadimg(menguser.getAvatarPic());
                    af.setPhone(menguser.getPhone());
                    af.setNickname(menguser.getNickName());
                    af.setLasttotal(act.getTotal());
                    af.setLastamount(act.getAmount());
                    af.insert();
                }

                //商家进账
                af.setId(null);

                //对于商家来说，该笔收款是推荐佣金
                af.setIotype(IotypeEnum.input.getVal());
                af.setXftype(XftypeEnum.tuijianfan.getVal());
                af.setXftypename(XftypeEnum.tuijianfan.getName());
                af.setIotype(IotypeEnum.input.getVal());

                af.setAmount(order.getSharefan());//实付金额
                af.setTotal(af.getAmount());//订单金额
                af.setRealpay(zero);//订单金额
                af.setDikou(zero);//订单金额

                af.setUid(fanuser.getId());
                Account act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", fanuser.getId()));
                if (act == null) {
                    act = accountService.initAccount(fanuser.getId(), fanuser.getMid(), fanuser.getMpid());
                }
                af.setHeadimg(fanuser.getAvatarPic());
                af.setPhone(fanuser.getPhone());
                af.setNickname(fanuser.getNickName());
                af.setLasttotal(act.getTotal());
                af.setLastamount(act.getAmount());
                af.insert();

            } else if (fanuser != null && fanuser.getLeagueid() != null && fanuser.getAlevel() != null) {

                order.setLmfan(money.multiply(new BigDecimal(0.6)));
                order.setPtfan(money.multiply(new BigDecimal(0.4)));
                order.setSharefan(money.multiply(new BigDecimal(0)));

                order.setFanuid(null);
                order.setSharefan(null);
                order.setPtfan(money);

                //返盟主
                af.setId(null);
                //对于盟主来说，该笔收款是代理收款
                af.setIotype(IotypeEnum.input.getVal());
                af.setXftype(XftypeEnum.tuijianfan.getVal());
                af.setXftypename(XftypeEnum.tuijianfan.getName());
                af.setAmount(order.getLmfan());//实付金额

                af.setTotal(af.getAmount());//订单金额
                af.setRealpay(zero);//订单金额
                af.setDikou(zero);//订单金额

                User menguser = userService.selectById(fanuser.getLeagueid());
                Account act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", menguser.getId()));
                if (act == null) {
                    act = accountService.initAccount(menguser.getId(), menguser.getMid(), menguser.getMpid());
                }
                af.setUid(menguser.getId());
                af.setHeadimg(menguser.getAvatarPic());
                af.setPhone(menguser.getPhone());
                af.setNickname(menguser.getNickName());
                af.setLasttotal(act.getTotal());
                af.setLastamount(act.getAmount());
                af.insert();

            } else {
                logger.debug("--------------------------------------kcdkaitong not mch not lianmeng");
            }
        } else {
            order.setSharefan(null);
            order.setPtfan(money);
        }
        logger.debug("--------------------------------------order/mdan maf opt");

        //=========平台=========
        //平台收款，确认通知里处理
        MaccountFlow maf = new MaccountFlow();
        maf.setAmount(order.getRealpay());// 实付金额
        maf.setMamount(zero);// 赠送金额（营销金额）

        maf.setUid(order.getUid());
        maf.setMid(order.getMid());
        maf.setMpid(order.getMpid());
        maf.setCreatetime(new Date());
        maf.setTradetime(new Date());
        maf.setState(1);//未确认
        maf.setIsConfirm(-1);//未确认

        maf.setIotype(IotypeEnum.input.getVal());//1:入账账
        //对于平台来说，该笔收款是平台会员代理销售
        maf.setXftype(XftypeEnum.sell.getVal());

        maf.setRemark(order.getGoodsName() + "【平台代理销售款】");
        maf.setSn(order.getOrderNo());
        maf.insert();

        order.setCreateday(Integer.parseInt(DateUtil.getToday("YYYYMMdd")));
        order.insert();
        logger.debug("--------------------------------------order/mdan come 999");

        if (order.getRealpay().doubleValue() > 0)
            json.setInfo(getShoukuanMap(order, order.getGoodsName()));

        return json;
    }

}
